package com.baosu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baosu.Exception.BusinessException;
import com.baosu.domain.Article;
import com.baosu.domain.Result;
import com.baosu.domain.Tag;
import com.baosu.service.TagService;
import com.baosu.mapper.TagMapper;
import com.baosu.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService{

    @Autowired
    private TagMapper tagMapper;

    @Override
    public Result<Page> pageTagList(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);

        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        if(name != null){
            queryWrapper.like(Tag::getName,name);
        }
        this.page(pageInfo, queryWrapper);
        return Result.ok(pageInfo);
    }

    @Override
    public Result getByArtucleId(Long id) {
        List<String> tags = tagMapper.getByArticleId(id);
        return Result.ok(tags);
    }

    @Override
    public Result deleteTag(List<Long> ids) {
        int count = tagMapper.selectTagAndArticle(ids);
        if(count > 0){
            throw new BusinessException(false, "标签下有文章，不可删除");
        }
        tagMapper.deleteBatchIds(ids);
        return Result.ok(null).message("删除标签成功");
    }

    @Override
    public Result getArticleByTag(int pagenum, int pagesize, Long tagId) {
        Page<Article> page = new Page<>(pagenum, pagesize);
        List<Article> articles = tagMapper.getArticleByTag(page, tagId);
        for (Article article : articles) {
            String content = article.getContent();
            String prefix = StringUtil.setArticlePrefix(content);
            article.setPrefix(prefix);
        }
        page.setRecords(articles);
        return Result.ok(page);
    }

    @Override
    public Result<List> getArticleCount() {
        List<Tag> tags = tagMapper.getArticleCount();
        return Result.ok(tags);
    }
}




